//
//  UIApplication+LBAddition.m
//  LBUIKit
//
//  Created by WuShiHai on 19/5/24.
//  Copyright (c) 2019 Lebbay. All rights reserved.
//

#import "UIApplication+LBAddition.h"
#import <LBFoundation/LBFoundation.h>

@implementation UIApplication (LBAddition)

+ (UIViewController *)displayViewController {
    LBDebugLoggerMessage(LBFormatString(@"begin displayViewController: %@", [self keyWindow]), nil);
    return [self displayViewController:[self keyWindow].rootViewController
                         ignorePresent:NO];
}

+ (UIViewController *)displayViewController:(UIViewController *)controller
                              ignorePresent:(BOOL)ignorePresent {
    LBDebugLoggerMessage(LBFormatString(@"enter displayViewController: %@", controller), nil);
    if (!ignorePresent) {
        controller = [self presentedViewController:controller];
    }
    if ([controller isKindOfClass:[UINavigationController class]]) {
        return [[(UINavigationController *)controller viewControllers] lastObject];
    } else if ([controller isKindOfClass:[UITabBarController class]]) {
        return [self displayViewController:[(UITabBarController *)controller selectedViewController]
                             ignorePresent:YES];
    } else if ([controller isKindOfClass:[UIViewController class]]) {
        return controller;
    } else {
        return controller;
    }
}

+ (NSString *)displayPageName {
    UIViewController *vc = [UIApplication displayViewController];
    SEL selector = NSSelectorFromString(@"pageName");
    if ([[vc class]respondsToSelector:selector]) {
        NSString *pageName = ((NSString * (*)(id, SEL))[[vc class] methodForSelector:selector])([vc class], selector);
        return pageName;
    }else{
        return NSStringFromClass([vc class]);
    }
}

+ (UIViewController *)presentedViewController:(UIViewController *)controller {
    if (LBRunningInAppExtension()) {
        return nil;
    }
    
    UIViewController *presentedController = controller.presentedViewController;
    while (presentedController && ![presentedController isBeingDismissed]) {
        controller = presentedController;
        presentedController = controller.presentedViewController;
    }
    
    return controller;
}

+ (NSArray *)blackListForDisplayPresentViewController {
    static NSArray *whiteList = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        whiteList = @[
//                      @"RCTModalHostViewController",
//                      @"UIInputWindowController",
                      ];
    });
    
    return whiteList;
}

+ (UIWindow *)keyWindow {
    return [UIApplication sharedApplication].keyWindow;
}

@end
